package com.ruoyi.web.controller.TiebaFavorites.controller;

import java.util.List;
import java.util.Arrays;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.web.controller.TiebaFavorites.domain.TiebaFavorites;
import com.ruoyi.web.controller.TiebaFavorites.mapper.TiebaFavoritesMapper;
import com.ruoyi.web.controller.TiebaFavorites.service.ITiebaFavoritesService;
import com.ruoyi.web.controller.TiebaFavorites.vo.TiebaFavoritesReqVo;
import com.ruoyi.web.controller.TiebaPosts.domain.TiebaPosts;
import com.ruoyi.web.controller.TiebaPosts.mapper.TiebaPostsMapper;
import io.swagger.models.auth.In;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 分享功能Controller
 *
 * @author yong
 * @date 2025-03-09
 */
@Api(tags = "用户-点赞")
@RestController
@RequestMapping("/TiebaFavorites/TiebaFavorites")
public class TiebaFavoritesController extends BaseController {
    @Autowired
    private ITiebaFavoritesService tiebaFavoritesService;

    @Resource
    private TiebaFavoritesMapper favoritesMapper;

    @Resource
    private TiebaPostsMapper postsMapper;

    /**
     * 查询点赞功能列表
     */
    @ApiOperation("查询点赞功能列表")
    @PreAuthorize("@ss.hasPermi('TiebaFavorites:TiebaFavorites:list')")
    @GetMapping("/list")
    public TableDataInfo list(TiebaFavorites tiebaFavorites) {
        startPage();
        tiebaFavorites.setUserId(getUserId());
        tiebaFavorites.setStatus(1);
        List<TiebaFavorites> list = tiebaFavoritesService.selectTiebaFavoritesList(tiebaFavorites);
        return getDataTable(list);
    }

    /**
     * 查询分享功能列表
     */
    @ApiOperation("点赞/取消点赞")
    @PreAuthorize("@ss.hasPermi('TiebaFavorites:TiebaFavorites:toggle')")
    @PostMapping("/toggle")
    public AjaxResult toggleFavorite(@RequestBody TiebaFavoritesReqVo reqVo) {
        Long userId = getUserId();
        Long postId = reqVo.getPostId();

        // 1. 检查帖子是否存在
        TiebaPosts post = postsMapper.selectById(postId);
        if (post == null) {
            return AjaxResult.error("帖子不存在");
        }

        // 2. 查询是否已有记录
        TiebaFavorites favorite = favoritesMapper.selectOne(
                new LambdaQueryWrapper<TiebaFavorites>()
                        .eq(TiebaFavorites::getUserId, userId)
                        .eq(TiebaFavorites::getPostId, postId)
        );

        // 3. 存在记录：切换状态
        if (favorite != null) {
            int newStatus = favorite.getStatus() == 1 ? 0 : 1;
            favorite.setStatus(newStatus);
            favoritesMapper.updateById(favorite);

            // 更新帖子的点赞数
            UpdateWrapper<TiebaPosts> updateWrapper = new UpdateWrapper<>();
            if (newStatus == 1) {
                updateWrapper.set("love_count", post.getLoveCount() + 1);
            } else {
                updateWrapper.set("love_count", Math.max(post.getLoveCount() - 1, 0)); // 防止负数
            }
            updateWrapper.eq("id", postId);
            postsMapper.update(null, updateWrapper);

            return AjaxResult.success(newStatus == 1 ? "点赞成功" : "取消点赞成功");
        }
        // 4. 不存在记录：插入新记录
        else {
            TiebaFavorites newFavorite = new TiebaFavorites();
            newFavorite.setUserId(userId);
            newFavorite.setPostId(postId);
            newFavorite.setDeptId(getDeptId());
            newFavorite.setStatus(1);

            try {
                favoritesMapper.insert(newFavorite);

                // 更新帖子的点赞数
                UpdateWrapper<TiebaPosts> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("love_count", post.getLoveCount() + 1);
                updateWrapper.eq("id", postId);
                postsMapper.update(null, updateWrapper);

                // 获取新插入记录的ID
                Long newFavoriteId = newFavorite.getId();

                return AjaxResult.success("点赞成功，新记录ID: " + newFavoriteId);
            } catch (DuplicateKeyException e) {
                // 唯一键冲突：说明并发插入，重新处理
                return toggleFavorite(reqVo);
            }
        }
    }
}
